package net.guoyixian.admin.service;

import java.io.IOException;
import java.util.Set;

import net.guoyixian.admin.mapper.SysManagersMapper;
import net.guoyixian.admin.pojo.SysManagers;
import net.guoyixian.common.datasource.DataSource;
import net.guoyixian.common.datasource.DataSource.SourceType;
import net.guoyixian.common.redis.RedisKeyPrefixUtils;
import net.guoyixian.common.redis.RedisService;
import net.guoyixian.common.web.JsonUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

/**
 * 用户service
 * 
 */
@Service
public class SysManagersService {
	@Autowired
	private SysManagersMapper sysManagersMapper;

	@Autowired
	private RedisService redisService;

	/**
	 * 查找用户角色
	 * 
	 * @param username
	 * @return
	 * @throws IOException 
	 */
	public Set<String> findRoles(String username){
		Set<String> roleSets = null;
		String roles = redisService.get(RedisKeyPrefixUtils.ROLE_ADMIN_PREFIX+username);
		if(!StringUtils.isEmpty(roles)){
			roleSets=JsonUtils.StrToSet(roles);
		}else{
			roleSets = sysManagersMapper.findRoles(username);
			redisService.set(RedisKeyPrefixUtils.ROLE_ADMIN_PREFIX+username, JsonUtils.ObjectToStr(roleSets));
		}
		return roleSets;
	}

	/**
	 * 查找用户权限
	 */
	public Set<String> findPermissions(String username) {
		Set<String> permissionSet = null;
		String permissions = redisService.get(RedisKeyPrefixUtils.PERMISSION_ADMIN_PREFIX+username);
		if(!StringUtils.isEmpty(permissions)){
			permissionSet=JsonUtils.StrToSet(permissions);
		}else{
			permissionSet = sysManagersMapper.findPermissions(username);
			redisService.set(RedisKeyPrefixUtils.PERMISSION_ADMIN_PREFIX+username, JsonUtils.ObjectToStr(permissionSet));
		}
		return permissionSet;
	}

	/**
	 * 根据用户名查找用户
	 * 
	 * @param username
	 * @return
	 */
	public SysManagers queryByUsername(String username) {
		return sysManagersMapper.queryByUsername(username);
	}

	@DataSource(SourceType.SLAVE)
	public PageList<SysManagers> queryList(PageBounds bounds, String username, String realname) {
		return sysManagersMapper.queryList(bounds, username, realname);
	}

	public void save(SysManagers managers) {
		sysManagersMapper.save(managers);
	};
}
